package com.example.chess.utils;

import android.media.AudioAttributes;
import android.media.SoundPool;

import com.example.chess.ChessApplication;
import com.example.chess.R;

public final class SoundEngine implements SoundPool.OnLoadCompleteListener {

    private SoundPool soundPool;
    private int soundId;

    public static SoundEngine create() {
        return new SoundEngine();
    }

    private SoundEngine() {
        initialize();
    }

    private void initialize() {
        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build();
        soundPool = new SoundPool.Builder()
                .setMaxStreams(2)
                .setAudioAttributes(attributes)
                .build();
        soundPool.setOnLoadCompleteListener(this);
    }

    public void prepareResource() {
        soundPool.load(ChessApplication.getContext(), R.raw.sound, 1);
    }

    @Override
    public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
        //success
        if (status == 0)
            soundId = sampleId;
    }

    public void playSoundEffect() {
        if (soundId != 0)
            soundPool.play(soundId, 1f, 1f, 1, 0, 1f);
    }

    public void release() {
        if (soundPool != null) {
            soundPool.autoPause();
            soundPool.unload(soundId);
            soundId = 0;
            soundPool.release();
        }
    }
}
